package service

import (
	"encoding/json"
	"fmt"
	"gin/CloudRestaurant/dao"
	"gin/CloudRestaurant/model"
	"gin/CloudRestaurant/param"
	"gin/CloudRestaurant/tool"
	_ "github.com/aliyun/alibaba-cloud-sdk-go"
	"github.com/aliyun/alibaba-cloud-sdk-go/services/dysmsapi"
	"math/rand"
	"time"
)

type MemberService struct {

}

func (ms *MemberService)SmsLogin(loginparam param.SmsLoginParam) *model.Member  {
	// 1获取手机号和验证码
	// 2 验证手机号+验证码是否正确
	md := dao.MemberDao{tool.DBEngine}
	sms := md.ValidateSmsCode(loginparam.Phone,loginparam.Code)
	if sms.Id ==0{
		fmt.Println("------验证码错误")
		return nil
	}
	// 3 根据手机号member表中查询记录
	member := md.QuerByPhone(loginparam.Phone)
	if member.Id !=0{

		return member
	}
	// 4 新建一个member记录 并保存
	user := model.Member{}
	user.UserName = loginparam.Phone
	user.Mobile = loginparam.Phone
	user.RegisterTime = time.Now().Unix()
	user.Id = md.InsertMemver(user)
   return  &user
}




// 给指定手机号发送短信
func (ms *MemberService) Sendcode(phone string) bool  {
	// 1 产生一个验证码
	code := fmt.Sprintf("%04v",rand.New(rand.NewSource(time.Now().UnixNano())).Int31n(10000))
	fmt.Println("收到的电话为 :"+phone+"\t" +"验证码为: "+code)

	// 2调用阿里云sdk 完成发送
	config := tool.GetConf().Sms
	client, err := dysmsapi.NewClientWithAccessKey(config.RegionId,config.AppKey,config.AppSecret)
	if err!= nil{
		fmt.Println(err.Error())
		return false
	}
	request := dysmsapi.CreateSendSmsRequest()
	request.Scheme = "https"
	request.SignName = config.SignName
	request.TemplateCode = config.TemplateCode
	request.PhoneNumbers = phone
	par,err := json.Marshal(map[string]interface{}{
		"code":code,
	})
	request.TemplateParam = string(par)
	response,err := client.SendSms(request)
	fmt.Println(response)
	if err!=nil{
		fmt.Println(err.Error())
		return false
	}

	// 3 接收返回结果，并判断发送状态
	// 短信验证码发送成功
	if response.Code == "OK"{
		// 将验证码保存到数据库当中
		smsCode := model.SmsCode{Phone: phone,Code:code,BizId: response.BizId,CreateTime: time.Now().Unix()}
		memberDao := dao.MemberDao{tool.DBEngine}
		result := memberDao.InsertCode(smsCode)
		return result >0
	}
	return false



}
